{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "FLAGS = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "init_learning_rate = tf.placeholder(tf.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [],
   "source": [
    "def swish(x):\n",
    "  return x * tf.nn.sigmoid(x)\n",
    "def selu(x):\n",
    "  with tf.name_scope('elu') as scope:\n",
    "    alpha = 1.6732632423543772848170429916717\n",
    "    scale = 1.0507009873554804934193349852946\n",
    "    return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))\n",
    "def relu(x):\n",
    "    return tf.nn.relu(x)\n",
    "def activation(x):\n",
    "  return swish(x)\n",
    "def initialize(shape, stddev=0.1):\n",
    "  return tf.truncated_normal(shape, stddev=stddev)\n",
    "# Create the model\n",
    "L1_units_count = 100\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "#tf.shape(x)  [100, 784]\n",
    "# exponetial lr decay\n",
    "epoch_steps = tf.to_int64(tf.div(60000, tf.shape(x)[0]))\n",
    "global_step = tf.train.get_or_create_global_step()\n",
    "current_epoch = global_step//epoch_steps\n",
    "decay_times = current_epoch \n",
    "current_learning_rate = tf.multiply(init_learning_rate, \n",
    "                                    tf.pow(0.575, tf.to_float(decay_times)))\n",
    "\n",
    "W_1 = tf.Variable(initialize([784, L1_units_count], \n",
    "                             stddev=np.sqrt(2/784)))\n",
    "b_1 = tf.Variable(tf.constant(0.001, shape=[L1_units_count]))\n",
    "logits_1 = tf.matmul(x, W_1) + b_1\n",
    "output_1 = activation(logits_1)\n",
    "\n",
    "L2_units_count = 10 \n",
    "W_2 = tf.Variable(initialize([L1_units_count, \n",
    "                              L2_units_count], \n",
    "                             stddev=np.sqrt(2/L1_units_count)))\n",
    "b_2 = tf.Variable(tf.constant(0.001, shape=[L2_units_count]))\n",
    "logits_2 = tf.matmul(output_1, W_2) + b_2  \n",
    "\n",
    "y = logits_2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "l2_loss = tf.nn.l2_loss(W_1) + tf.nn.l2_loss(W_2)\n",
    "total_loss = cross_entropy + 4e-5*l2_loss\n",
    "\n",
    "optimizer = tf.train.AdamOptimizer(current_learning_rate)\n",
    "gradients = optimizer.compute_gradients(total_loss)\n",
    "train_step = optimizer.apply_gradients(gradients)\n",
    "\n",
    "train_step = tf.train.AdamOptimizer(\n",
    "    current_learning_rate).minimize(\n",
    "    total_loss, global_step=global_step)\n",
    "# weight decay      \n",
    "#0 0 0 0 1 0 0 0 0\n",
    "#0 1 0 0 0 0 0 0 0\n",
    "# 还记得不？不要把graph定义写到图里面\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "sess = tf.InteractiveSession()\n",
    "tf.global_variables_initializer().run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 0.416776, l2_loss: 301.982239, total loss: 0.428856\n",
      "0.9313\n",
      "step 200, entropy loss: 0.218962, l2_loss: 400.049591, total loss: 0.234964\n",
      "0.9451\n",
      "step 300, entropy loss: 0.201397, l2_loss: 498.424561, total loss: 0.221334\n",
      "0.9516\n",
      "step 400, entropy loss: 0.210943, l2_loss: 587.727600, total loss: 0.234452\n",
      "0.9597\n",
      "step 500, entropy loss: 0.235890, l2_loss: 682.474365, total loss: 0.263189\n",
      "0.9609\n",
      "step 600, entropy loss: 0.065228, l2_loss: 743.775452, total loss: 0.094979\n",
      "0.9492\n",
      "step 700, entropy loss: 0.018804, l2_loss: 737.528992, total loss: 0.048305\n",
      "0.969\n",
      "step 800, entropy loss: 0.053654, l2_loss: 729.247620, total loss: 0.082824\n",
      "0.972\n",
      "step 900, entropy loss: 0.135735, l2_loss: 725.159973, total loss: 0.164741\n",
      "0.9718\n",
      "step 1000, entropy loss: 0.094086, l2_loss: 734.138855, total loss: 0.123452\n",
      "0.9729\n",
      "step 1100, entropy loss: 0.021498, l2_loss: 741.305176, total loss: 0.051150\n",
      "0.9712\n",
      "step 1200, entropy loss: 0.085296, l2_loss: 739.630859, total loss: 0.114881\n",
      "0.9732\n",
      "step 1300, entropy loss: 0.022851, l2_loss: 729.835449, total loss: 0.052044\n",
      "0.9767\n",
      "step 1400, entropy loss: 0.091367, l2_loss: 721.004517, total loss: 0.120207\n",
      "0.9768\n",
      "step 1500, entropy loss: 0.121691, l2_loss: 714.419128, total loss: 0.150267\n",
      "0.9759\n",
      "step 1600, entropy loss: 0.028765, l2_loss: 707.342957, total loss: 0.057059\n",
      "0.9768\n",
      "step 1700, entropy loss: 0.031744, l2_loss: 698.922363, total loss: 0.059701\n",
      "0.9787\n",
      "step 1800, entropy loss: 0.015215, l2_loss: 690.018066, total loss: 0.042816\n",
      "0.9769\n",
      "step 1900, entropy loss: 0.096364, l2_loss: 684.305542, total loss: 0.123736\n",
      "0.9795\n",
      "step 2000, entropy loss: 0.030415, l2_loss: 677.755432, total loss: 0.057525\n",
      "0.9795\n",
      "step 2100, entropy loss: 0.084613, l2_loss: 672.795044, total loss: 0.111525\n",
      "0.9808\n",
      "step 2200, entropy loss: 0.029076, l2_loss: 666.992493, total loss: 0.055756\n",
      "0.9807\n",
      "step 2300, entropy loss: 0.014277, l2_loss: 661.191711, total loss: 0.040724\n",
      "0.98\n",
      "step 2400, entropy loss: 0.010451, l2_loss: 654.775818, total loss: 0.036642\n",
      "0.9809\n",
      "step 2500, entropy loss: 0.028027, l2_loss: 650.544373, total loss: 0.054049\n",
      "0.982\n",
      "step 2600, entropy loss: 0.040976, l2_loss: 646.157410, total loss: 0.066822\n",
      "0.9824\n",
      "step 2700, entropy loss: 0.043358, l2_loss: 641.220093, total loss: 0.069007\n",
      "0.9804\n",
      "step 2800, entropy loss: 0.009573, l2_loss: 636.071350, total loss: 0.035016\n",
      "0.9801\n",
      "step 2900, entropy loss: 0.010603, l2_loss: 631.945251, total loss: 0.035881\n",
      "0.9812\n",
      "step 3000, entropy loss: 0.003432, l2_loss: 626.884155, total loss: 0.028507\n",
      "0.9818\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for step in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  lr = 1e-2\n",
    "  _, loss, l2_loss_value, total_loss_value, current_lr_value = \\\n",
    "      sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss, \n",
    "                current_learning_rate], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, \n",
    "                          init_learning_rate:lr})\n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    #print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys}))\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9818\n"
     ]
    }
   ],
   "source": [
    "# Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
